package main

import (
	"flag"
	"html/template"
	"log"
	"net/http"
	"os"

	"git.oschina.net/alwaysking/pclive/server/PCLiveServer"
	"git.oschina.net/alwaysking/pclive/server/PCLiveWeb"
)

var logger *log.Logger

// 首页和404页面
func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
	var path string
	if r.URL.Path == "/" {
		//http.Redirect(w, r, "Index.html", http.StatusFound)
		path = "html/Index.html"
	} else {
		path = "html" + r.URL.Path
	}

	t, err := template.ParseFiles(path)
	if err != nil {
		t, err = template.ParseFiles("html/404.html")
		if err != nil {
			logger.Println("无效地址" + r.URL.Path)
		}
	}

	t.Execute(w, nil)
}

func main() {
	//test()
	// 获取运行新参数
	LogPath := flag.String("log", "./PCLive-server.log", "Log File Path")
	flag.Parse()

	// 创建日志文件
	logfile, err := os.OpenFile(*LogPath, os.O_RDWR|os.O_CREATE, 0666)
	if err != nil {
		return
	}
	logger = log.New(logfile, "\r\n", log.Ldate|log.Ltime|log.Llongfile)
	logger.Println("程序开始")
	defer logger.Println("程序结束")

	// 启动PCLIve的服务
	PCLiveServer.InitPCLiveServer(logger)
	PCLiveWeb.PcliveWebInit()

	// 开启http服务
	http.HandleFunc("/PCLive/", PCLiveWeb.PCLiveWebServer)
	http.HandleFunc("/", NotFoundHandler)
	http.Handle("/css/", http.FileServer(http.Dir("html")))
	http.Handle("/js/", http.FileServer(http.Dir("html")))
	http.Handle("/img/", http.FileServer(http.Dir("html")))

	err = http.ListenAndServe("0.0.0.0:7789", nil)
	if err != nil {
		logger.Println("启动服务失败")
		logger.Println(err)
		return
	}
}
